import os
import pickle

from ..constant import CATALOG_DIRECTORY

class CatalogForm:
    pass


class CatalogBasic:
    def __init__(self, name):
        self.name = name
        self.rows = []
    
    def insert(self, row: CatalogForm):
        self.rows.append(row)
        # TODO: 是否rows里面的结果需要排序
        self.dump()
    
    def delete(self, lambda_condition):
        i = 0
        while i < len(self.rows):
            if lambda_condition(self.rows[i]):
                self.rows.pop(i)
                i -= 1
            i += 1

        self.dump()
        
    def select(self, lambda_condition):
        return [row for row in self.rows if lambda_condition(row)]

    def update(self, lambda_condition):
        self.delete(lambda_condition)
        self.insert(lambda_condition)

    def load(self):
        filename = os.path.join(CATALOG_DIRECTORY, self.name)
        if not os.path.exists(filename):
            return
        data = bytearray()
        with open(filename, 'rb') as f:
            while True:
                chunk = f.read(256)
                if not chunk:
                    break
                data += chunk
        self.rows = pickle.loads(data)

    def dump(self):
        if not os.path.exists(CATALOG_DIRECTORY):
            os.mkdir(CATALOG_DIRECTORY)
        filename = os.path.join(CATALOG_DIRECTORY, self.name)
        
        # w+b 表示追加写
        with open(filename, 'w+b') as f:
            f.write(pickle.dumps(self.rows))
            # 虽然有代价，但是一定要保证数据能够完全刷到磁盘上(会阻塞)
            os.fsync(f.fileno())
            
